package com.jsz.peini.service.order;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.activity.ActivityInfo;
import com.jsz.peini.bean.activity.ActivityUser;
import com.jsz.peini.bean.coupon.CouponHistory;
import com.jsz.peini.bean.coupon.CouponHistoryExample;
import com.jsz.peini.bean.coupon.CouponHistoryExample.Criteria;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.coupon.CouponRange;
import com.jsz.peini.bean.coupon.CouponSeller;
import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.order.ConversionDetail;
import com.jsz.peini.bean.order.GoldHistory;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.order.OrderInfoExample;
import com.jsz.peini.bean.order.OrderSeller;
import com.jsz.peini.bean.order.OrderSellerExample;
import com.jsz.peini.bean.seller.SellerDiscount;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.user.UserAccount;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserLogin;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.NumberFormatUtil;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.mapper.activity.ActivityInfoMapper;
import com.jsz.peini.mapper.activity.ActivityUserMapper;
import com.jsz.peini.mapper.coupon.CouponHistoryMapper;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.coupon.CouponRangeMapper;
import com.jsz.peini.mapper.coupon.CouponSellerMapper;
import com.jsz.peini.mapper.coupon.CouponUserMapper;
import com.jsz.peini.mapper.order.ConversionDetailMapper;
import com.jsz.peini.mapper.order.GoldHistoryMapper;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.order.OrderSellerMapper;
import com.jsz.peini.mapper.seller.SellerDiscountMapper;
import com.jsz.peini.mapper.seller.SellerInfoMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserAccountMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;
import com.jsz.peini.server.thread.TaskFinishTimerTask;
import com.jsz.peini.service.seller.SellerInfoService;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.sms.SmsSend;

@Service
public class OrderInfoService {
	private static final Logger logger = LoggerFactory.getLogger(OrderInfoService.class);
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private CouponHistoryMapper couponHistoryMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private TaskInfoMapper taskInfoMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private GoldHistoryMapper goldHistoryMapper;
	@Resource
	private ConversionDetailMapper conversionDetailMapper;
	@Resource
	private UserAccountMapper userAccountMapper;
	@Resource
	private OrderSellerMapper orderSellerMapper;
	@Resource
	private CouponSellerMapper couponSellerMapper;
	@Resource
	private SellerInfoMapper sellerInfoMapper;
	@Resource
	private CouponInfoMapper couponInfoMapper;
	@Resource
	private UserSmsMapper userSmsMapper;
	@Resource
	private ActivityInfoMapper activityInfoMapper;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private SellerDiscountMapper sellerDiscountMapper;
	@Resource
	private CouponRangeMapper couponRangeMapper;
	
	@Resource
	private ActivityUserMapper  activityUserMapper;
	@Resource
	private SellerInfoService sellerInfoService;
	
	
	//陪你买单通知id
	private static final String SMSTaskBuy = "53006"; 

	public HashMap<String,Object> selectByOrderId(Long orderId){
		HashMap<String,Object> orderMap = orderInfoMapper.selectByOrderId(orderId);
		return orderMap;
	}
	
	public List<LinkedHashMap<String, Object>> getOrderInfoList(OrderInfo orderInfo){
		List<LinkedHashMap<String,Object>> orderInfoList=orderInfoMapper.getOrderInfoList(orderInfo);
		return orderInfoList;
	}	
		
	public List<HashMap<String,Object>> selectPayByOrderId(Long orderId){
		List<HashMap<String,Object>> orderList = orderInfoMapper.selectPayByOrderId(orderId);
		return orderList;
	}
	
	public List<HashMap<String,Object>> selectPayDetailByOrderId(int sellerId){
		List<HashMap<String,Object>> payList = orderInfoMapper.selectPayDetailByOrderId(sellerId);
		return payList;
	}
	
	public int updateOrderStatusByOrderId(OrderInfo orderInfo){
		int result = orderInfoMapper.updateOrderStatusByOrderId(orderInfo);
		return result;
	}
	
	/**
	 * 保存任务订单
	 * @author Han Guohong
	 * @param request
	 * @param userId
	 * @param taskId
	 * @param sellerInfoId
	 * @param totalMoney
	 * @param exclusiveMoney
	 * @param payType
	 * @param couponId
	 * @param rangId
	 * @return
	 */
	@Transactional
	public LinkedHashMap<String, Object> saveTaskOrder(HttpServletRequest request,
			String userId,
			Integer taskId,
			Integer sellerInfoId,
			Double totalMoney,
			Double exclusiveMoney,
			Integer payType,//1金币；2微信；3支付宝
			Integer couponId,
			Integer rangId
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			OrderInfo orderInfo = new OrderInfo();
			
			//查询是否提交过订单
			OrderInfoExample example = new OrderInfoExample();
			com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
			criteria.andOrderTypeEqualTo(1);
			criteria.andSellerInfoIdEqualTo(sellerInfoId);
			criteria.andTaskInfoIdEqualTo(taskId);
			criteria.andUserIdEqualTo(userId);
			List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(example);
			if(orderInfos.size()>0){
				orderInfo = orderInfos.get(0);
				if(orderInfo.getOrderStatus() >= 1){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "该订单已经支付过了，请勿重复支付!");
					return infoMap;
				}
			}
			
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			UserLogin userLogin = userInfo.getUserLogin();
			
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(sellerInfoId);
			
			TaskInfo taskInfo = null;
			taskInfo = taskInfoMapper.selectByPrimaryKey(taskId);
			if(!taskInfo.getUserId().equals(userId) && !taskInfo.getOtherUserId().equals(userId)){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
				return infoMap;
			}
			if(!taskInfo.getSellerInfoId().toString().trim().equals(sellerInfoId.toString().trim())){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
				return infoMap;
			}
			
			if(taskInfo.getUserId().equals(userId)){
				orderInfo.setOtherId(taskInfo.getOtherUserId());
			}else{
				orderInfo.setOtherId(taskInfo.getUserId());
			}
			
			orderInfo.setOtherBuy(taskInfo.getOtherBuy());
			orderInfo.setTaskInfoId(taskId);
			orderInfo.setOrderType(1);//任务订单
			
			orderInfo.setSellerInfoId(sellerInfoId);
			orderInfo.setUserId(userId);
			
			orderInfo.setOrderStatus(0);
			orderInfo.setAllMoney((int)(totalMoney*100));
			
			BigDecimal goldNum = new BigDecimal("0");
			BigDecimal alipay = new BigDecimal("0");
			BigDecimal wxpay = new BigDecimal("0");
			
			SellerDiscount discount = new SellerDiscount();
			discount.setSellerInfoId(sellerInfoId);
			discount = sellerInfoService.getSellerDiscount(discount);
			
			goldNum = new BigDecimal(discount.getGoldNum()).divide(new BigDecimal("100"));
			alipay = new BigDecimal(discount.getZfbNum()).divide(new BigDecimal("100"));
			wxpay = new BigDecimal(discount.getWeixinNum()).divide(new BigDecimal("100"));
			
			/*BigDecimal goldNum = new BigDecimal("0");
			BigDecimal alipay = new BigDecimal("0");
			BigDecimal wxpay = new BigDecimal("0");
			int week = DateTimeUtils.getWeek();
			SellerDiscountExample sellerDiscountExample = new SellerDiscountExample();
			com.jsz.peini.bean.seller.SellerDiscountExample.Criteria sellerDiscountCriteria = sellerDiscountExample.createCriteria();
			sellerDiscountCriteria.andStartNumLessThanOrEqualTo(week);
			sellerDiscountCriteria.andEndNumGreaterThanOrEqualTo(week);
			sellerDiscountCriteria.andSellerInfoIdEqualTo(sellerInfoId);
			List<SellerDiscount> list = sellerDiscountMapper.selectByExample(sellerDiscountExample);
			for (SellerDiscount dis : list) {
				String frontStr = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				String startTime = frontStr+" "+dis.getStartTime();
				String endTime = frontStr+" "+dis.getEndTime();
				
				Date now = new Date();
				if((DateTimeUtils.formatString2Date(startTime, "yyyy-MM-dd HH:mm").before(now) && DateTimeUtils.formatString2Date(endTime, "yyyy-MM-dd HH:mm").after(now))
						|| startTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm")) || endTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm"))
						){
					goldNum = new BigDecimal(dis.getGoldNum()).divide(new BigDecimal("100"));
					alipay = new BigDecimal(dis.getZfbNum()).divide(new BigDecimal("100"));
					wxpay = new BigDecimal(dis.getWeixinNum()).divide(new BigDecimal("100"));
				}
			}*/
			
			BigDecimal payMoney = new BigDecimal("0");
			switch (payType) {
			case 1:
				if(goldNum.doubleValue() == 0 || goldNum.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(goldNum).add(exclusive);
					
					orderInfo.setDiscount(goldNum.multiply(new BigDecimal("100")).toString());
				}
				break;
			case 2:
				if(wxpay.doubleValue() == 0 || wxpay.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(wxpay).add(exclusive);
					
					orderInfo.setDiscount(wxpay.multiply(new BigDecimal("100")).toString());
				}
				break;
			case 3:
				if(alipay.doubleValue() == 0 || alipay.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(totalMoney);
				}else{
					BigDecimal total = new BigDecimal(totalMoney);
					BigDecimal exclusive = new BigDecimal(exclusiveMoney);
					payMoney = total.subtract(exclusive).multiply(alipay).add(exclusive);
					
					orderInfo.setDiscount(alipay.multiply(new BigDecimal("100")).toString());
				}
				break;
			default:
				break;
			}
			
			if(couponId != null && couponId != 0){
				if(rangId == null || rangId == 0){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "参数缺失");
					return infoMap;
				}
				
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("userId", userId);
				paramMap.put("sellerId", sellerInfoId);
				paramMap.put("payMoney", payMoney.doubleValue());
				paramMap.put("rangId", rangId);
				paramMap.put("couponId", couponId);
				List<HashMap<String, Object>> cList = couponInfoMapper.getCouponInfoByPay(paramMap);
				if(cList.size() > 0){
					HashMap<String, Object> couponMap = cList.get(0);
					
					orderInfo.setCouponId(couponId);
					
					CouponUser couponUser = couponUserMapper.selectByPrimaryKey(couponMap.get("getId").toString());
					
					orderInfo.setCouponUserId(couponUser.getId());
					
					if(orderInfo.getId() == null){
						int orderId = orderInfoMapper.insertSelective(orderInfo);
					}
					
					//couponUser.setCouponNum(0);
					couponUser.setCouponRangId(rangId);
					couponUserMapper.updateByPrimaryKey(couponUser);
					
					//插入优惠券流水表，为冻结状态
					CouponHistory chis = new CouponHistory();
					chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
					chis.setCreateTime(new Date());
					chis.setUserId(userId);
					chis.setOpType(1);
					chis.setIsFinish(0);
					chis.setValNum(1l);
					chis.setHisType(3);
					chis.setParamId(orderInfo.getId().toString());
					chis.setIsDel(1);
					chis.setCouponId(couponId);
					chis.setCouponUserId(couponUser.getId());
					couponHistoryMapper.insertSelective(chis);
					
					//优惠券信息表使用数量加1
					/*CouponInfo info = new CouponInfo();
					info.setId(couponId);
					info.setUsenum(+1l);
					PeiniUtils.useCoupons.add(info);*/
					
					orderInfo.setCouponMoney(Integer.parseInt(couponMap.get("couponMoney").toString()));
					
					CouponRange range = couponRangeMapper.selectByPrimaryKey(rangId);
					
					if(payMoney.doubleValue() <= Integer.parseInt(couponMap.get("couponMoney").toString())){
						payMoney = new BigDecimal("0");
						
						BigDecimal officialMoney = new BigDecimal(range.getOfficialMoney());
						if(payMoney.doubleValue()<=officialMoney.doubleValue()){
							orderInfo.setOfficialAssume(payMoney);
							orderInfo.setSellerIncome(payMoney);
						}else{
							orderInfo.setOfficialAssume(officialMoney);
							orderInfo.setSellerIncome(payMoney);
						}
						
						orderInfo.setSellerIncome(payMoney.add(new BigDecimal(range.getOfficialMoney())));
					}else{
						payMoney = payMoney.subtract(new BigDecimal(couponMap.get("couponMoney").toString()));
						
						orderInfo.setOfficialAssume(new BigDecimal(range.getOfficialMoney()));
						
						orderInfo.setSellerIncome(payMoney.add(new BigDecimal(range.getOfficialMoney())));
					}
					/*if(payMoney.doubleValue() <= couponInfo.getCouponMoney()){
						payMoney = new BigDecimal("0");
					}else{
						payMoney = payMoney.subtract(new BigDecimal(couponInfo.getCouponMoney()));
					}*/
				}
				
				
				/*CouponUserExample cuExample = new CouponUserExample();
				cuExample.createCriteria().andCouponIdEqualTo(couponId).andCouponNumEqualTo(1);
				cuExample.setOrderByClause("get_time asc");
				List<CouponUser> cuList = couponUserMapper.selectByExample(cuExample);
				CouponUser couponUser = cuList.get(0);
				
				orderInfo.setCouponUserId(couponUser.getId());*/
			}else{
				if(orderInfo.getCouponId() != null && orderInfo.getCouponId() != 0){
					CouponUser couponUser = couponUserMapper.selectByPrimaryKey(orderInfo.getCouponUserId());
					if(couponUser != null){
						couponUser.setCouponNum(1);
						couponUser.setCouponRangId(null);
						couponUserMapper.updateByPrimaryKey(couponUser);
					}
					
					CouponHistoryExample historyExample = new CouponHistoryExample();
					Criteria hisCriteria = historyExample.createCriteria();
					hisCriteria.andCouponUserIdEqualTo(orderInfo.getCouponUserId());
					hisCriteria.andUserIdEqualTo(orderInfo.getUserId());
					hisCriteria.andParamIdEqualTo(orderInfo.getId().toString());
					hisCriteria.andHisTypeEqualTo(11);
					hisCriteria.andOpTypeEqualTo(0);
					hisCriteria.andIsFinishEqualTo(0);
					List<CouponHistory> histories = couponHistoryMapper.selectByExample(historyExample);
					if(histories.size() > 0){
						CouponHistory his = histories.get(0);
						couponHistoryMapper.deleteByPrimaryKey(his.getHisId());
					}
					
					orderInfo.setCouponId(null);
					orderInfo.setCouponUserId(null);
					orderInfo.setCouponMoney(null);
					
				}
				
				orderInfo.setOfficialAssume(new BigDecimal("0"));
				//orderInfo.setSellerIncome(payMoney);
				orderInfo.setSellerIncome(NumberFormatUtil.ceilFormat(payMoney));
			}
			
			payMoney = payMoney.multiply(new BigDecimal(100));
			
			if(payMoney.doubleValue() < 0){
				payMoney = new BigDecimal("0");
			}
			orderInfo.setPayMoney((int)Math.ceil(payMoney.doubleValue()));
			orderInfo.setExclusiveMoney(new BigDecimal(exclusiveMoney));
			orderInfo.setUserPhone(userLogin.getUserName());
			orderInfo.setOrderTime(new Date());
			
			orderInfo.setContractPhone(sellerInfo.getSellerPhone());
			
			if(orderInfo.getId() != null){
				if(StringUtils.isBlank(orderInfo.getOrderCode())){
					String code = "";
					code += orderInfo.getOrderType();
					SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
					code += sdf.format(new Date());
					String codeStr = String.valueOf(orderInfo.getId());
					if(codeStr.length()> 6){
						codeStr = codeStr.substring(codeStr.length()-6);
					}else if(codeStr.length() < 6){
						for (int i = 0; i < 6-codeStr.length(); i++) {
							code += "0";
						}
					}
					code += codeStr;
					orderInfo.setOrderCode(code);
				}
				orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
			}else {
				orderInfoMapper.insertSelective(orderInfo);
				String code = "";
				code += orderInfo.getOrderType();
				SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
				code += sdf.format(new Date());
				String codeStr = String.valueOf(orderInfo.getId());
				if(codeStr.length()> 6){
					codeStr = codeStr.substring(codeStr.length()-6);
				}else if(codeStr.length() < 6){
					for (int i = 0; i < 6-codeStr.length(); i++) {
						code += "0";
					}
				}
				code += codeStr;
				orderInfo.setOrderCode(code);
				orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
			}
			
			if(taskInfo.getOtherBuy() != 3){
				taskInfo.setOrderId(orderInfo.getId());
				taskInfo.setOtherOrderId(orderInfo.getId());
			}else{
				if(taskInfo.getUserId().equals(orderInfo.getUserId())){
					taskInfo.setOrderId(orderInfo.getId());
				}else{
					taskInfo.setOtherOrderId(orderInfo.getId());
				}
			}
			taskInfoMapper.updateByPrimaryKey(taskInfo);
			
			OrderSellerExample orSellerExample = new OrderSellerExample();
			com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
			orCriteria.andSellerIdEqualTo((long)sellerInfoId);
			orCriteria.andOrderTypeEqualTo(1);
			orCriteria.andTaskIdEqualTo((long)taskId);
			List<OrderSeller> list2 = orderSellerMapper.selectByExample(orSellerExample);
			if(list2.size() == 0){
				
			}else{
				OrderSeller orderSeller = list2.get(0);
				
				/*if(orderSeller.getUserId()!= null && !orderSeller.getUserId().equals(userId) && orderSeller.getOtherId() == null){//发布者已经提交过了
					orderSeller.setOtherId(userId);
					Long allMoney = orderSeller.getTotalMoney() == null ? 0 : orderSeller.getTotalMoney();
					Long pMoney = orderSeller.getPayMoney() == null ? 0 : orderSeller.getPayMoney();
					orderSeller.setTotalMoney(allMoney+orderInfo.getAllMoney());
					orderSeller.setPayMoney(pMoney+orderInfo.getPayMoney());
					orderSellerMapper.updateByPrimaryKey(orderSeller);
				}else if(orderSeller.getOtherId() != null && !orderSeller.getOtherId().equals(userId) && orderSeller.getUserId() == null){
					orderSeller.setUserId(userId);
					Long allMoney = orderSeller.getTotalMoney() == null ? 0 : orderSeller.getTotalMoney();
					Long pMoney = orderSeller.getPayMoney() == null ? 0 : orderSeller.getPayMoney();
					orderSeller.setTotalMoney(allMoney+orderInfo.getAllMoney());
					orderSeller.setPayMoney(pMoney+orderInfo.getPayMoney());
					orderSellerMapper.updateByPrimaryKey(orderSeller);
				}else if(orderSeller.getUserId() == null && orderSeller.getOtherId() == null){
					switch (taskInfo.getOtherBuy()) {
					case 1:
						if(taskInfo.getUserId().equals(userId)){//发起人
							orderSeller.setUserId(userId);
							orderSeller.setOtherId(taskInfo.getOtherUserId());
							orderSeller.setTotalMoney((long)orderInfo.getAllMoney());
							orderSeller.setPayMoney((long)orderInfo.getPayMoney());
						}
						break;
					case 2:
						if(taskInfo.getOtherUserId().equals(userId)){//参与人
							orderSeller.setUserId(userId);
							orderSeller.setOtherId(taskInfo.getOtherUserId());
							orderSeller.setTotalMoney((long)orderInfo.getAllMoney());
							orderSeller.setPayMoney((long)orderInfo.getPayMoney());
						}
						break;
					case 3:
						if(taskInfo.getUserId().equals(userId)){//发起人
							orderSeller.setUserId(userId);
							orderSeller.setTotalMoney((long)orderInfo.getAllMoney());
							orderSeller.setPayMoney((long)orderInfo.getPayMoney());
						}else if(taskInfo.getOtherUserId().equals(userId)){
							orderSeller.setOtherId(taskInfo.getOtherUserId());
							orderSeller.setTotalMoney((long)orderInfo.getAllMoney());
							orderSeller.setPayMoney((long)orderInfo.getPayMoney());
						}
						break;
					default:
						break;
					}
					orderSellerMapper.updateByPrimaryKey(orderSeller);
				}*/
			}
			
			infoMap.put("orderIdStr", orderInfo.getId().toString());
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	/**
	 * 普通商家订单		
	 * @author Han Guohong
	 * @param request
	 * @param userId
	 * @param sellerInfoId
	 * @param totalMoney
	 * @param exclusiveMoney
	 * @param payType
	 * @param couponId
	 * @param rangId
	 * @return
	 */
	@Transactional
	public LinkedHashMap<String, Object> saveSellerOrder(HttpServletRequest request,
			String userId,
			Integer sellerInfoId,
			Double totalMoney,
			Double exclusiveMoney,
			Integer payType,//1金币；2微信；3支付宝
			Integer couponId,
			Integer rangId
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try{
			OrderInfo orderInfo = new OrderInfo();
			
			//查询是否提交过订单
			OrderInfoExample example = new OrderInfoExample();
			com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
			criteria.andOrderTypeEqualTo(3);
			criteria.andSellerInfoIdEqualTo(sellerInfoId);
			criteria.andUserIdEqualTo(userId);
			criteria.andOrderStatusEqualTo(0);
			List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(example);
			if(orderInfos.size()>0){
				orderInfo = orderInfos.get(0);
				/*if(orderInfo.getOrderStatus() >= 1){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "该订单已经支付过了，请勿重复支付!");
					return infoMap;
				}*/
			}
			
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			UserLogin userLogin = userInfo.getUserLogin();
			
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(sellerInfoId);
			
			orderInfo.setOrderType(3);//普通商家订单
			
			orderInfo.setSellerInfoId(sellerInfoId);
			orderInfo.setUserId(userId);
			
			orderInfo.setOrderStatus(0);
			orderInfo.setSellerStatus(0);
			orderInfo.setAllMoney((int)(totalMoney*100));
			
			BigDecimal goldNum = new BigDecimal("0");
			BigDecimal alipay = new BigDecimal("0");
			BigDecimal wxpay = new BigDecimal("0");
			
			SellerDiscount discount = new SellerDiscount();
			discount.setSellerInfoId(sellerInfoId);
			discount = sellerInfoService.getSellerDiscount(discount);
			
			goldNum = new BigDecimal(discount.getGoldNum()).divide(new BigDecimal("100"));
			alipay = new BigDecimal(discount.getZfbNum()).divide(new BigDecimal("100"));
			wxpay = new BigDecimal(discount.getWeixinNum()).divide(new BigDecimal("100"));
			
			/*int week = DateTimeUtils.getWeek();
			SellerDiscountExample sellerDiscountExample = new SellerDiscountExample();
			com.jsz.peini.bean.seller.SellerDiscountExample.Criteria sellerDiscountCriteria = sellerDiscountExample.createCriteria();
			sellerDiscountCriteria.andStartNumLessThanOrEqualTo(week);
			sellerDiscountCriteria.andEndNumGreaterThanOrEqualTo(week);
			sellerDiscountCriteria.andSellerInfoIdEqualTo(sellerInfoId);
			List<SellerDiscount> list = sellerDiscountMapper.selectByExample(sellerDiscountExample);
			for (SellerDiscount dis : list) {
				String frontStr = DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd");
				String startTime = frontStr+" "+dis.getStartTime();
				String endTime = frontStr+" "+dis.getEndTime();
				
				Date now = new Date();
				if((DateTimeUtils.formatString2Date(startTime, "yyyy-MM-dd HH:mm").before(now) && DateTimeUtils.formatString2Date(endTime, "yyyy-MM-dd HH:mm").after(now))
						|| startTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm")) || endTime.equals(DateTimeUtils.formatDateTime2String(now, "yyyy-MM-dd HH:mm"))
						){
					goldNum = new BigDecimal(dis.getGoldNum()).divide(new BigDecimal("100"));
					alipay = new BigDecimal(dis.getZfbNum()).divide(new BigDecimal("100"));
					wxpay = new BigDecimal(dis.getWeixinNum()).divide(new BigDecimal("100"));
				}
			}*/
			
			BigDecimal payMoney = new BigDecimal("0");
			switch (payType) {
			case 1:
				if(goldNum.doubleValue() == 0 || goldNum.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(String.valueOf(totalMoney));
				}else{
					BigDecimal total = new BigDecimal(String.valueOf(totalMoney));
					BigDecimal exclusive = new BigDecimal(String.valueOf(exclusiveMoney));
					payMoney = total.subtract(exclusive).multiply(goldNum).add(exclusive);
					
					orderInfo.setDiscount(goldNum.multiply(new BigDecimal("100")).toString());
				}
				break;
			case 2:
				if(wxpay.doubleValue() == 0 || wxpay.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(String.valueOf(totalMoney));
				}else{
					BigDecimal total = new BigDecimal(String.valueOf(totalMoney));
					BigDecimal exclusive = new BigDecimal(String.valueOf(exclusiveMoney));
					payMoney = total.subtract(exclusive).multiply(wxpay).add(exclusive);
					
					orderInfo.setDiscount(wxpay.multiply(new BigDecimal("100")).toString());
				}
				break;
			case 3:
				if(alipay.doubleValue() == 0 || alipay.doubleValue() == 1){//没有折扣
					payMoney = new BigDecimal(String.valueOf(totalMoney));
				}else{
					BigDecimal total = new BigDecimal(String.valueOf(totalMoney));
					BigDecimal exclusive = new BigDecimal(String.valueOf(exclusiveMoney));
					payMoney = total.subtract(exclusive).multiply(alipay).add(exclusive);
					
					orderInfo.setDiscount(alipay.multiply(new BigDecimal("100")).toString());
				}
				break;
			default:
				break;
			}
			
			if(couponId != null && couponId != 0){
				if(rangId == null || rangId == 0){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "参数缺失");
					return infoMap;
				}
				
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("userId", userId);
				paramMap.put("sellerId", sellerInfoId);
				paramMap.put("payMoney", payMoney.doubleValue());
				paramMap.put("rangId", rangId);
				paramMap.put("couponId", couponId);
				List<HashMap<String, Object>> cList = couponInfoMapper.getCouponInfoByPay(paramMap);
				if(cList.size() > 0){
					HashMap<String, Object> couponMap = cList.get(0);
					
					orderInfo.setCouponId(couponId);
					
					/*CouponUserExample cuExample = new CouponUserExample();
					cuExample.createCriteria().andCouponIdEqualTo(couponId).andCouponNumEqualTo(1);
					cuExample.setOrderByClause("get_time asc");
					List<CouponUser> cuList = couponUserMapper.selectByExample(cuExample);
					CouponUser couponUser = cuList.get(0);*/
					CouponUser couponUser = couponUserMapper.selectByPrimaryKey(couponMap.get("getId").toString());
					
					orderInfo.setCouponUserId(couponUser.getId());
					
					if(orderInfo.getId() == null){
						int orderId = orderInfoMapper.insertSelective(orderInfo);
					}
					
					//couponUser.setCouponNum(0);
					couponUser.setCouponRangId(rangId);
					couponUserMapper.updateByPrimaryKey(couponUser);
					
					//插入优惠券流水表，为冻结状态
					CouponHistory chis = new CouponHistory();
					chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
					chis.setCreateTime(new Date());
					chis.setUserId(userId);
					chis.setOpType(0);
					chis.setIsFinish(0);
					chis.setValNum(1l);
					chis.setHisType(11);
					chis.setParamId(orderInfo.getId().toString());
					chis.setIsDel(1);
					chis.setCouponId(couponId);
					chis.setCouponUserId(couponUser.getId());
					couponHistoryMapper.insertSelective(chis);
					
					orderInfo.setCouponMoney(Integer.parseInt(couponMap.get("couponMoney").toString()));
					
					CouponRange range = couponRangeMapper.selectByPrimaryKey(rangId);
					
					if(payMoney.doubleValue() <= Integer.parseInt(couponMap.get("couponMoney").toString())){
						/*BigDecimal cpMoney = new BigDecimal(couponMap.get("couponMoney").toString());
						//payMoney = cpMoney.subtract(payMoney);
						
						BigDecimal sellerMoney = new BigDecimal(range.getSellerMoney());
						
						if(payMoney.doubleValue() > sellerMoney.doubleValue()){
							orderInfo.setOfficialAssume(payMoney.subtract(sellerMoney));
							orderInfo.setSellerIncome(payMoney.subtract(sellerMoney));
						}else{
							orderInfo.setOfficialAssume(new BigDecimal("0"));
							orderInfo.setSellerIncome(new BigDecimal("0"));
						}*/
						
						//TODO  后期需要根据承担额度更改
						orderInfo.setOfficialAssume(payMoney);
						orderInfo.setSellerIncome(payMoney);
						
						payMoney = new BigDecimal("0");
					}else{
						payMoney = payMoney.subtract(new BigDecimal(couponMap.get("couponMoney").toString()));
					
						orderInfo.setOfficialAssume(new BigDecimal(range.getOfficialMoney()));
						
						orderInfo.setSellerIncome(payMoney.add(new BigDecimal(range.getOfficialMoney())));
					}
				}
			}else{
				if(orderInfo.getCouponId() != null && orderInfo.getCouponId() != 0){
					CouponUser couponUser = couponUserMapper.selectByPrimaryKey(orderInfo.getCouponUserId());
					if(couponUser != null){
						couponUser.setCouponNum(1);
						couponUser.setCouponRangId(null);
						couponUserMapper.updateByPrimaryKey(couponUser);
					}
					
					CouponHistoryExample historyExample = new CouponHistoryExample();
					Criteria hisCriteria = historyExample.createCriteria();
					hisCriteria.andCouponUserIdEqualTo(orderInfo.getCouponUserId());
					hisCriteria.andUserIdEqualTo(orderInfo.getUserId());
					hisCriteria.andParamIdEqualTo(orderInfo.getId().toString());
					hisCriteria.andHisTypeEqualTo(11);
					hisCriteria.andOpTypeEqualTo(0);
					hisCriteria.andIsFinishEqualTo(0);
					List<CouponHistory> histories = couponHistoryMapper.selectByExample(historyExample);
					if(histories.size() > 0){
						CouponHistory his = histories.get(0);
						couponHistoryMapper.deleteByPrimaryKey(his.getHisId());
					}
					
					orderInfo.setCouponId(null);
					orderInfo.setCouponUserId(null);
					orderInfo.setCouponMoney(null);
					
				}
				
				orderInfo.setOfficialAssume(new BigDecimal("0"));
				
				/*String pm = String.valueOf(payMoney);
				if(pm.lastIndexOf(".") > pm.length()-3){
					String pm1 = pm.substring(0, endIndex)
				}*/
				
				orderInfo.setSellerIncome(NumberFormatUtil.ceilFormat(payMoney));
			}
			
			payMoney = payMoney.multiply(new BigDecimal(100));
			
			if(payMoney.doubleValue() < 0){
				payMoney = new BigDecimal("0");
			}
			//orderInfo.setPayMoney(payMoney.intValue());
			orderInfo.setPayMoney((int)Math.ceil(payMoney.doubleValue()));
			orderInfo.setExclusiveMoney(new BigDecimal(exclusiveMoney));
			orderInfo.setUserPhone(userLogin.getUserName());
			orderInfo.setOrderTime(new Date());
			
			orderInfo.setContractPhone(sellerInfo.getSellerPhone());
			
			if(orderInfo.getId() != null){
				if(StringUtils.isBlank(orderInfo.getOrderCode())){
					String code = "";
					code += orderInfo.getOrderType();
					SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
					code += sdf.format(new Date());
					String codeStr = String.valueOf(orderInfo.getId());
					if(codeStr.length()> 6){
						codeStr = codeStr.substring(codeStr.length()-6);
					}else if(codeStr.length() < 6){
						for (int i = 0; i < 6-codeStr.length(); i++) {
							code += "0";
						}
					}
					code += codeStr;
					orderInfo.setOrderCode(code);
				}
				orderInfo.setTaskInfoId(orderInfo.getId().intValue());
				orderInfoMapper.updateByPrimaryKey(orderInfo);
			}else {
				orderInfoMapper.insertSelective(orderInfo);
				String code = "";
				code += orderInfo.getOrderType();
				SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
				code += sdf.format(new Date());
				String codeStr = String.valueOf(orderInfo.getId());
				if(codeStr.length()> 6){
					codeStr = codeStr.substring(codeStr.length()-6);
				}else if(codeStr.length() < 6){
					for (int i = 0; i < 6-codeStr.length(); i++) {
						code += "0";
					}
				}
				code += codeStr;
				orderInfo.setOrderCode(code);
				orderInfo.setTaskInfoId(orderInfo.getId().intValue());
				orderInfoMapper.updateByPrimaryKey(orderInfo);
			}
			
			OrderSeller orderSeller = new OrderSeller();
			OrderSellerExample orderSellerExample = new OrderSellerExample();
			orderSellerExample.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo(0).andOrderTypeEqualTo(3).andSellerIdEqualTo((long)sellerInfoId).andOrderStatusEqualTo(0);
			List<OrderSeller> orderSellerList = orderSellerMapper.selectByExample(orderSellerExample);
			if(orderSellerList.size() > 0){
				orderSeller = orderSellerList.get(0);
			}
			
			orderSeller.setTaskUserId(userId);
			orderSeller.setOrderStatus(0);
			orderSeller.setOrderTime(new Date());
			orderSeller.setOrderType(3);
			orderSeller.setSellerId((long)sellerInfoId);
			orderSeller.setTaskId((long)orderInfo.getId());
			orderSeller.setUserId(userInfo.getId());
			orderSeller.setUserImageHead(userInfo.getImageHead());
			orderSeller.setUserNickname(userInfo.getNickname());
			orderSeller.setTotalMoney((long)orderInfo.getAllMoney());
			orderSeller.setPayMoney((long)orderInfo.getPayMoney());
			orderSeller.setCodestr(orderInfo.getOrderCode());
			
			if(orderSellerList.size() > 0){
				orderSellerMapper.updateByPrimaryKey(orderSeller);
			}else {
				orderSellerMapper.insertSelective(orderSeller);	
			}
			
			String code = "";
			code += orderSeller.getOrderType();
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			code += sdf.format(new Date());
			String codeStr = String.valueOf(orderSeller.getId());
			if(codeStr.length()> 6){
				codeStr = codeStr.substring(codeStr.length()-6);
			}else if(codeStr.length() < 6){
				for (int i = 0; i < 6-codeStr.length(); i++) {
					code += "0";
				}
			}
			code += codeStr;
			orderSeller.setOrderCode(code);
			orderSellerMapper.updateByPrimaryKey(orderSeller);
			
			infoMap.put("orderIdStr", orderInfo.getId().toString());
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "成功");
		}catch(Exception e){
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	/**
	 * 订单通知
	 * @author Han Guohong
	 * @param title
	 * @return
	 */
	@Transactional
	public boolean notifyPayOrder(OrderInfo title) {
		boolean flag = true;
		try {
			if(title != null){
				logger.info("----------支付后续业务处理--------------");
				orderInfoMapper.updateByPrimaryKeySelective(title);
				if(title.getCouponId() != null){//优惠券后续处理
					String couponUserId = title.getCouponUserId();
					
					//更新优惠券历史表为已结束
					CouponHistoryExample example = new CouponHistoryExample();
					Criteria criteria = example.createCriteria();
					criteria.andCouponUserIdEqualTo(couponUserId);
					criteria.andUserIdEqualTo(title.getUserId());
					criteria.andParamIdEqualTo(title.getId().toString());
					List<CouponHistory> histories = couponHistoryMapper.selectByExample(example);
					CouponHistory his = histories.get(0);
					his.setIsFinish(1);
					couponHistoryMapper.updateByPrimaryKey(his);
					
					//如果用户的改优惠券数量为0
					/*CouponUserExample couponUserExample = new CouponUserExample();
					com.jsz.peini.bean.coupon.CouponUserExample.Criteria cuCriteria = couponUserExample.createCriteria();
					cuCriteria.andCouponIdEqualTo(couponId);
					cuCriteria.andUserIdEqualTo(title.getUserId());
					List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
					CouponUser couponUser = couponUsers.get(0);*/
					CouponUser couponUser = couponUserMapper.selectByPrimaryKey(couponUserId);
					couponUser.setCouponNum(0);
					couponUser.setSellerId(title.getSellerInfoId());
					couponUserMapper.updateByPrimaryKeySelective(couponUser);
					/*if(couponUser.getCouponNum() == 0){
						couponUserMapper.deleteByPrimaryKey(couponUser.getId());
					}*/
					
					CouponInfo couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
					SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(title.getSellerInfoId());
					
					//优惠券信息表使用数量加1
					CouponInfo info = new CouponInfo();
					info.setId(couponUser.getCouponId());
					info.setUsenum(+1l);
					PeiniUtils.useCoupons.add(info);
					
					CouponSeller couponSeller = new CouponSeller();
					couponSeller.setCityid(sellerInfo.getCityCode()==null ? "0" : sellerInfo.getCityCode().toString());
					couponSeller.setCouponId(couponInfo.getId());
					couponSeller.setLabelid(sellerInfo.getLabelsId());
					couponSeller.setProvinceid(sellerInfo.getProvinceid().toString());
					couponSeller.setSellerInfoId(title.getSellerInfoId());
					couponSeller.setTypeid(sellerInfo.getSellerType().toString());
					couponSeller.setCouponrangeid(couponUser.getCouponRangId());
					couponSellerMapper.insert(couponSeller);
				}

				if(title.getOrderType() == 1){//任务订单
					String otherBuyUser = "";
					int taskId = title.getTaskInfoId();
					TaskInfo taskInfo = taskInfoMapper.selectByPrimaryKey(taskId);
					
					int otherBuy = taskInfo.getOtherBuy();//1我买单；2他买单；3AA制
					
					switch (otherBuy) {
					case 1://任务结束
						taskInfo.setTaskStatus(3);
						taskInfo.setTaskOtherStatus(31);
						taskInfo.setTaskEndTime(new Date());
						taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
						
						//每人加3分
						String userId = taskInfo.getUserId();
						String otherId = taskInfo.getOtherUserId();
						
						UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
						int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
						if (taskNum+3 >= 1000) {
							userInfo.setTaskNum(1000);
						}else{
							userInfo.setTaskNum(taskNum+3);
						}
						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						
						userInfo = userInfoMapper.selectByPrimaryKey(otherId);
						taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
						if (taskNum+3 >= 1000) {
							userInfo.setTaskNum(1000);
						}else{
							userInfo.setTaskNum(taskNum+3);
						}
						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						break;
					case 2://任务结束
						taskInfo.setTaskStatus(3);
						taskInfo.setTaskOtherStatus(31);
						taskInfo.setTaskEndTime(new Date());
						taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
						
						//每人加3分
						userId = taskInfo.getUserId();
						otherId = taskInfo.getOtherUserId();
						
						userInfo = userInfoMapper.selectByPrimaryKey(userId);
						taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
						if (taskNum+3 >= 1000) {
							userInfo.setTaskNum(1000);
						}else{
							userInfo.setTaskNum(taskNum+3);
						}
						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						
						userInfo = userInfoMapper.selectByPrimaryKey(otherId);
						taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
						if (taskNum+3 >= 1000) {
							userInfo.setTaskNum(1000);
						}else{
							userInfo.setTaskNum(taskNum+3);
						}
						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						break;
					case 3:
						
						if(taskInfo.getUserId().equals(title.getUserId())){//我发布的任务(发布者买单)
							otherBuyUser = taskInfo.getOtherUserId();//获取接收人userid
							taskInfo.setTaskStatus(3);
							taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
							userId = taskInfo.getUserId();
							userInfo = userInfoMapper.selectByPrimaryKey(userId);
							taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
							if (taskNum+3 >= 1000) {
								userInfo.setTaskNum(1000);
							}else{
								userInfo.setTaskNum(taskNum+3);
							}
							userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
							userInfoMapper.updateByPrimaryKeySelective(userInfo);
							
							//判断对方是否已经付款
							OrderInfo otherOrderInfo = orderInfoMapper.selectUserOrderByUserId(otherBuyUser, taskId);
							if (otherOrderInfo == null || otherOrderInfo.getPayStatus().intValue() != 1) {
								TaskFinishTimerTask taskFinishTimerTask = new TaskFinishTimerTask();
								taskFinishTimerTask.setTaskId(taskId);
								taskFinishTimerTask.setPersonType(2);
								taskFinishTimerTask.setUserId(otherBuyUser);
								Timer timer = new Timer();
								timer.schedule(taskFinishTimerTask, 21600000);
								//timer.schedule(taskFinishTimerTask, 600000);
							}
							
							
						}else{//他发布的任务(接收者买单)
							otherBuyUser = taskInfo.getUserId();
							taskInfo.setTaskOtherStatus(31);
							taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
							otherId = taskInfo.getOtherUserId();
							userInfo = userInfoMapper.selectByPrimaryKey(otherId);
							taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
							if (taskNum+3 >= 1000) {
								userInfo.setTaskNum(1000);
							}else{
								userInfo.setTaskNum(taskNum+3);
							}
							userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
							userInfoMapper.updateByPrimaryKeySelective(userInfo);
							
							//判断对方是否已经付款
							OrderInfo otherOrderInfo = orderInfoMapper.selectUserOrderByUserId(otherBuyUser, taskId);
							if (otherOrderInfo == null || otherOrderInfo.getPayStatus().intValue() != 1) {
								TaskFinishTimerTask taskFinishTimerTask = new TaskFinishTimerTask();
								taskFinishTimerTask.setTaskId(taskId);
								taskFinishTimerTask.setPersonType(1);
								taskFinishTimerTask.setUserId(otherBuyUser);
								Timer timer = new Timer();
								timer.schedule(taskFinishTimerTask, 21600000);
								//timer.schedule(taskFinishTimerTask, 600000);
							} 
						}
						/*OrderInfoExample orderInfoExample = new OrderInfoExample();
						com.jsz.peini.bean.order.OrderInfoExample.Criteria orderCriteria = orderInfoExample.createCriteria();
						orderCriteria.andUserIdEqualTo(otherBuyUser);
						orderCriteria.andTaskInfoIdEqualTo(taskId);
						orderCriteria.andOrderStatusEqualTo(1);
						List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(orderInfoExample);
						if(orderInfos.size() > 0){*/
						//taskInfo.setTaskStatus(3);
						taskInfo = taskInfoMapper.selectByPrimaryKey(taskId);
						if ((taskInfo.getTaskStatus().intValue() == 3 || taskInfo.getTaskStatus().intValue() == 4) && (taskInfo.getTaskOtherStatus().intValue() == 31 || taskInfo.getTaskOtherStatus().intValue() == 41)) {
							taskInfo.setTaskEndTime(new Date());
							taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
						}
//						  
//						taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
						
						//每人加3分
//						userId = taskInfo.getUserId();
//						otherId = taskInfo.getOtherUserId();
						
//						userInfo = userInfoMapper.selectByPrimaryKey(userId);
//						taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
//						if (taskNum+3 >= 1000) {
//							userInfo.setTaskNum(1000);
//						}else{
//							userInfo.setTaskNum(taskNum+3);
//						}
//						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
//						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						
//						userInfo = userInfoMapper.selectByPrimaryKey(otherId);
//						taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
//						if (taskNum+3 >= 1000) {
//							userInfo.setTaskNum(1000);
//						}else{
//							userInfo.setTaskNum(taskNum+3);
//						}
//						userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
//						userInfoMapper.updateByPrimaryKeySelective(userInfo);
						//}
						break;
					default:
						break;
					}
					
					
					//更新店铺订单
					OrderSellerExample sellerExample = new OrderSellerExample();
					sellerExample.createCriteria().andTaskIdEqualTo((long)taskId).andOrderTypeEqualTo(1).andSellerIdEqualTo((long)title.getSellerInfoId());
					List<OrderSeller> orderSellers = orderSellerMapper.selectByExample(sellerExample);
					if(orderSellers.size() >= 0){
						OrderSeller orderSeller = orderSellers.get(0);
						/*Long allMoney = orderSeller.getTotalMoney() == null ? 0 : orderSeller.getTotalMoney();
						Long payMoney = orderSeller.getPayMoney() == null ? 0 : orderSeller.getPayMoney();
						orderSeller.setTotalMoney(allMoney+title.getAllMoney());
						orderSeller.setPayMoney(payMoney+title.getPayMoney());*/
						
						List<Integer> statusList = new ArrayList<Integer>();
						statusList.add(1);
						statusList.add(2);
						BigDecimal allMoney = new BigDecimal("0");
						BigDecimal pMoney = new BigDecimal("0");
						OrderInfoExample orExample = new OrderInfoExample();
						orExample.createCriteria().andOrderTypeEqualTo(1).andTaskInfoIdEqualTo(taskId).andSellerInfoIdEqualTo(title.getSellerInfoId()).andOrderStatusIn(statusList);
						List<OrderInfo> orderList = orderInfoMapper.selectByExample(orExample);
						
						String codeStr = "";
						for (OrderInfo info : orderList) {
							allMoney = allMoney.add(new BigDecimal(info.getAllMoney() == null ? "0" : info.getAllMoney().toString()));
							pMoney = pMoney.add(new BigDecimal(info.getPayMoney() == null ? "0" : info.getPayMoney().toString()));
							
							codeStr += info.getUserId()+","+info.getOrderCode()+";";
						}
						
						if(codeStr.endsWith(";")){
							codeStr = codeStr.substring(0, codeStr.length()-1);
						}
						
						orderSeller.setCodestr(codeStr);
						orderSeller.setTotalMoney(allMoney.longValue());
						orderSeller.setPayMoney(pMoney.longValue());
						//orderSellerMapper.updateByPrimaryKey(orderSeller);
						
						orderSeller.setOrderStatus(1);
						orderSellerMapper.updateByPrimaryKeyWithBLOBs(orderSeller);
						
						SmsSendUtil.sendSmsNotify(taskInfo.getSellerInfoId().toString(), orderSeller.getId().toString(), 22, "您的订单(订单号<a href='seller/orderDetail?orderId="+orderSeller.getId()+"'>"+orderSeller.getOrderCode()+"</a>)已完成付款");
						
						Date date=new Date();
						SellerInfo sellerInfo=sellerInfoMapper.getSellerInfoById(taskInfo.getSellerInfoId());
						SimpleDateFormat timeFormater = new SimpleDateFormat("MM-dd HH:mm");
						String str = timeFormater.format(date);
						if (sellerInfo.getWeathersms()==1 && sellerInfo.getSmsType() != null) {
							if(sellerInfo.getSmsType().indexOf("3")>=0||sellerInfo.getSmsType().indexOf("4")>=0){
								if (sellerInfo.getSmsText()!=null) {
									BigDecimal money = new BigDecimal("0");
									BigDecimal Paymoney = new BigDecimal("0");
									if(title.getAllMoney() != 0){
										money = new BigDecimal(title.getAllMoney());
										money = money.divide(new BigDecimal("100"));
									}
									if(title.getPayMoney() != 0){
										Paymoney = new BigDecimal(title.getPayMoney());
										Paymoney = Paymoney.divide(new BigDecimal("100"));
									}
									String ordercode=orderSeller.getOrderCode().substring(orderSeller.getOrderCode().length()-6,orderSeller.getOrderCode().length());
									Integer couponMoney=(title.getCouponMoney()==null?0:title.getCouponMoney());
									String param=sellerInfo.getSellerName()+","+str+","+ordercode+","+money+","+couponMoney+","+Paymoney;
									SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskBuy);
								}
							}
						}
						//消息推送
						JSONObject object = new JSONObject();
						object.put("title", "任务付款通知");
						object.put("type", 104);
						//给发起人推送消息
						if (otherBuy==1) {
							BigDecimal payM = new BigDecimal(orderSeller.getPayMoney());
							payM = payM.divide(new BigDecimal("100"));
							
							object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							object.put("paramId", title.getId()+","+taskId);//订单id，任务id
							UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(title.getUserId());
							AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
							
							if (!taskInfo.getOtherUserId().isEmpty()) {
								object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！快去评价一下本次任务吧~");
								UserInfo newuserInfo2 = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
								AppPush.sendPush(object,newuserInfo2.getUserPhone().split(","));
							}
							
							SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							
							if (!taskInfo.getOtherUserId().isEmpty()) {
								SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！快去评价一下本次任务吧~");
							}
						}else if(otherBuy==2){							
							BigDecimal payM = new BigDecimal(orderSeller.getPayMoney());
							payM = payM.divide(new BigDecimal("100"));
							
							object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							object.put("paramId", title.getId()+","+taskId);//订单id，任务id
							UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
							AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
							
							if (!taskInfo.getOtherUserId().isEmpty()) {
								object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！快去评价一下本次任务吧~");
								UserInfo newuserInfo2 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
								AppPush.sendPush(object,newuserInfo2.getUserPhone().split(","));
							}
							
							SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							
							if (!taskInfo.getOtherUserId().isEmpty()) {
								SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！快去评价一下本次任务吧~");
							}
						}else{
							String otherUserId=null;
							if (taskInfo.getUserId().equals(title.getUserId())) {
								otherUserId=taskInfo.getOtherUserId();
							}else {
								otherUserId=taskInfo.getUserId();
							}
							
							BigDecimal payM = new BigDecimal(orderSeller.getPayMoney());
							payM = payM.divide(new BigDecimal("100"));
							
							object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							object.put("paramId", title.getId()+","+taskId);//订单id，任务id
							UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(title.getUserId());
							logger.info("------------------------------------------------"+orderSeller.getPayMoney()+"金额"+payM);
							AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsNotify(title.getUserId(), title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务已成功付款"+payM+"元！快去评价一下本次任务吧~");
							
							/*if (!taskInfo.getOtherUserId().isEmpty()) {
								OrderInfo otherOrderInfo = orderInfoMapper.selectUserOrderByUserId(OtherUserId, taskId);
								if (otherOrderInfo == null || (otherOrderInfo.getPayStatus().intValue() != 1&&otherOrderInfo.getPayStatus().intValue() !=2)) {
									object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！完成付款即可评价本次任务~");
									UserInfo newuserInfo2 = userInfoMapper.selectByPrimaryKey(OtherUserId);
									AppPush.sendPush(object,newuserInfo2.getUserPhone().split(","));
								}
							}*/
							
							if(StringUtils.isNotBlank(otherUserId)){
								OrderInfo otherOrderInfo = orderInfoMapper.selectUserOrderByUserId(otherUserId, taskId);
								if (otherOrderInfo == null || (otherOrderInfo.getPayStatus() != 1 && otherOrderInfo.getPayStatus() !=2)) {
									object.put("content", "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！完成付款即可评价本次任务~");
									UserInfo newuserInfo2 = userInfoMapper.selectByPrimaryKey(otherUserId);
									AppPush.sendPush(object,newuserInfo2.getUserPhone().split(","));
									
									SmsSendUtil.sendSmsNotify(otherUserId, title.getId()+","+taskId, 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！完成付款即可评价本次任务~");
								}
							}
							
							/*if (!taskInfo.getOtherUserId().isEmpty()) {
								OrderInfo otherOrderInfo = orderInfoMapper.selectUserOrderByUserId(OtherUserId, taskId);
								if (otherOrderInfo == null || (otherOrderInfo.getPayStatus().intValue() != 1&&otherOrderInfo.getPayStatus().intValue() !=2)) {
									SmsSendUtil.sendSmsNotify(OtherUserId, taskInfo.getId().toString(), 104, "您参与的“"+taskInfo.getSellerInfoName()+"”任务对方已付款！完成付款即可评价本次任务~");
								}
							}*/
						}
					}
					//if(title.getPayType() != 1){
						UserAccount userAccount = userAccountMapper.selectByUserId(title.getUserId());					
						//更新土豪榜排名
						updatePayRank(title, userAccount);
					//}
				}else if(title.getOrderType() == 3){
					//更新店铺订单
					OrderSellerExample sellerExample = new OrderSellerExample();
					sellerExample.createCriteria().andTaskIdEqualTo((long)title.getId()).andOrderTypeEqualTo(3).andSellerIdEqualTo((long)title.getSellerInfoId()).andUserIdEqualTo(title.getUserId()).andOrderStatusEqualTo(0);
					List<OrderSeller> orderSellers = orderSellerMapper.selectByExample(sellerExample);
					if(orderSellers.size() > 0){
						OrderSeller orderSeller = orderSellers.get(0);
						
						List<Integer> statusList = new ArrayList<Integer>();
						statusList.add(1);
						statusList.add(2);
						OrderInfoExample orExample = new OrderInfoExample();
						orExample.createCriteria().andOrderTypeEqualTo(3).andTaskInfoIdEqualTo(title.getId().intValue()).andSellerInfoIdEqualTo(title.getSellerInfoId()).andOrderStatusIn(statusList);
						List<OrderInfo> orderList = orderInfoMapper.selectByExample(orExample);
						
						//TODO 确认订单是否需要逗号
						String codeStr = "";
						for (OrderInfo info : orderList) {
							codeStr += info.getUserId()+","+info.getOrderCode()+";";
						}
						if(codeStr.endsWith(";")){
							codeStr = codeStr.substring(0, codeStr.length()-1);
						}
						
						orderSeller.setCodestr(codeStr);
						orderSeller.setOrderStatus(1);
						orderSellerMapper.updateByPrimaryKeyWithBLOBs(orderSeller);
						
						//给店铺发送消息
						Date date=new Date();
						SmsSendUtil.sendSmsNotify(orderSeller.getSellerId().toString(), orderSeller.getId().toString(), 22, "您的订单(订单号<a href='seller/orderDetail?orderId="+orderSeller.getId()+"'>"+orderSeller.getOrderCode()+"</a>)已完成付款");
						
						SellerInfo sellerInfo=sellerInfoMapper.selectByPrimaryKey(title.getSellerInfoId());
						
						BigDecimal pMoney = new BigDecimal(orderSeller.getPayMoney());
						pMoney = pMoney.divide(new BigDecimal("100"));
						
						//消息推送（给买单人）
						JSONObject object = new JSONObject();
						object.put("title", "买单成功通知");
						object.put("content", "您已成功在\""+sellerInfo.getSellerName()+"\"店铺付款"+pMoney+"元！快去评价一下店铺吧~");
						object.put("paramId", title.getId()+","+sellerInfo.getId());
						object.put("type", 101);
						UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(title.getUserId());
						AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
						
						SmsSendUtil.sendSmsNotify(orderSeller.getUserId(), title.getId()+","+sellerInfo.getId(), 101, "您已成功在“"+sellerInfo.getSellerName()+"”店铺付款"+pMoney+"元！快去评价一下店铺吧~");
						sellerInfo=sellerInfoMapper.getSellerInfoById(sellerInfo.getId());
						SimpleDateFormat timeFormater = new SimpleDateFormat("MM-dd HH:mm");
						String str = timeFormater.format(date);
						if (sellerInfo.getWeathersms()!=null &&sellerInfo.getWeathersms() ==1) {
							if(StringUtils.isNotBlank(sellerInfo.getSmsType())){
								if(sellerInfo.getSmsType().indexOf("3")>=0||sellerInfo.getSmsType().indexOf("4")>=0){
									if (sellerInfo.getSmsText()!=null) {
										BigDecimal money = new BigDecimal("0");
										BigDecimal Paymoney = new BigDecimal("0");
										if(title.getAllMoney() != 0){
											money = new BigDecimal(title.getAllMoney());
											money = money.divide(new BigDecimal("100"));
										}
										if(title.getPayMoney() != 0){
											Paymoney = new BigDecimal(title.getPayMoney());
											Paymoney = Paymoney.divide(new BigDecimal("100"));
										}
										String ordercode=orderSeller.getOrderCode().substring(orderSeller.getOrderCode().length()-6,orderSeller.getOrderCode().length());
										Integer couponMoney=(title.getCouponMoney()==null?0:title.getCouponMoney());
										String param=sellerInfo.getSellerName()+","+str+","+ordercode+","+money+","+couponMoney+","+Paymoney;
										SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskBuy);
									}
								}
							}
						}
					}
					
					//if(title.getPayType() != 1){
						UserAccount userAccount = userAccountMapper.selectByUserId(title.getUserId());					
						//更新土豪榜排名
						updatePayRank(title, userAccount);
					//}
				}else if(title.getOrderType() == 6){//金币充值订单
					GoldHistory history = new GoldHistory();
					history.setCreateTime(new Date());
					history.setHisId(UUID.randomUUID().toString().replace("-", ""));
					history.setHisType(9);
					history.setIsDel(1);
					history.setIsFinish(1);
					history.setOpType(1);
					history.setParamId(title.getId().toString());
					history.setUserId(title.getUserId());
					ConversionDetail detail = conversionDetailMapper.selectByPrimaryKey(title.getTaskInfoId());
					history.setValNum((long)detail.getGoldNum()*100);
					goldHistoryMapper.insertSelective(history);	
					UserAccount userAccount = userAccountMapper.selectByUserId(title.getUserId());
					
					//消息推送
					JSONObject object = new JSONObject();
			        object.put("title", "系统消息");
			        object.put("content", "充值成功！"+detail.getGoldNum()+"金币已放置您的财富中~点击可查看");
			        object.put("type", 110);
			        object.put("paramId",history.getHisId() );
			        UserInfo userInfo2 = userInfoMapper.selectByPrimaryKey(title.getUserId());
					AppPush.sendPush(object,userInfo2.getUserPhone().split(","));
					
					SmsSendUtil.sendSmsNotify(title.getUserId(), history.getHisId(), 110, "充值成功！"+detail.getGoldNum()+"金币已放置您的财富中~点击可查看");
					
					//更新金币排行榜
					updateGoldRank(history, userAccount);
				}else if(title.getOrderType() == 7){//活动报名
					ActivityInfo info = activityInfoMapper.selectByPrimaryKey(title.getParamId());
					Date date=new Date();
					String userId = title.getUserId();
					String acId = info.getAcId();		
					String regCnt = RedisUtil.get(RedisConstants.ACTIVITY+acId);
					Integer rCnt = Integer.parseInt(regCnt);
					
					RedisUtil.set(RedisConstants.ACTIVITY+acId,String.valueOf(rCnt+1));
					info.setRegUserCnt(rCnt+1);
//					if(info.getPersonMinNum() <= (rCnt+1) && info.getAcStatus() == 0){
//						info.setAcStatus(1);
//					}
//					
//					if(info.getPersonMaxNum() == (rCnt + 1) && info.getAcStatus() == 1){
//						info.setAcStatus(-1);
//					}
					if(date.getTime()>info.getSignStartTime().getTime()&&date.getTime()<info.getStartTime().getTime())
					{
						if(info.getIsperson()==1)
						{
							if(info.getPersonMaxNum()==(rCnt + 1))
							{
								info.setAcStatus(4);
							}
							else
							{
								info.setAcStatus(0);
							}
						}
						else
						{
							info.setAcStatus(0);
						}
						
					}
					if(date.getTime()>info.getSignEndTime().getTime()&&date.getTime()<info.getStartTime().getTime())
					{
						info.setAcStatus(2);
					}
					if(date.getTime()>info.getStartTime().getTime()&&date.getTime()<info.getEndTime().getTime())
					{
						info.setAcStatus(1);
					}
					if(date.getTime()>info.getEndTime().getTime())
					{
						info.setAcStatus(-1);
					}
					activityInfoMapper.updateByPrimaryKey(info);
					
					ActivityUser acUser = new ActivityUser();
					acUser.setAcId(acId);
					acUser.setUserId(userId);
					acUser.setRegId(UUID.randomUUID().toString().replace("-", ""));
					acUser.setRegTime(new Date());
					acUser.setActivityInfo(info);
					activityUserMapper.insertSelective(acUser);
					
					//将数据插入redis缓存
					HashMap<byte[], byte[]> acUserMap = new HashMap<byte[], byte[]>();
					acUserMap.put(userId.getBytes(), SerializeUtil.serialize(acUser));
					RedisUtil.hmset((RedisConstants.ACTIVITY_USER+acId).getBytes(), acUserMap);
					
					//将数据放入数据库待处理队列
//					PeiniUtils.activityUserList.add(acUser);
				}else if(title.getOrderType() == 8){//老客户赠送金币订单
					/*GoldHistory history = new GoldHistory();
					history.setCreateTime(new Date());
					history.setHisId(UUID.randomUUID().toString().replace("-", ""));
					history.setHisType(11);
					history.setIsDel(1);
					history.setIsFinish(1);
					history.setOpType(1);
					history.setParamId(title.getId().toString());
					history.setUserId(title.getUserId());
					history.setValNum(Long.parseLong(title.getDiscount()));
					goldHistoryMapper.insertSelective(history);	
					
					UserAccount userAccount = userAccountMapper.selectByUserId(title.getUserId());
					
					BigDecimal valNum = new BigDecimal(history.getValNum());
					valNum = valNum.divide(new BigDecimal("100"));
					
					//消息推送
					JSONObject object = new JSONObject();
			        object.put("title", "金币赠送通知");
			        object.put("content", "恭喜！系统赠送了您"+valNum+"金币，快去我的财富查看吧~点击可查看");
			        object.put("type", 111);
			        object.put("paramId",history.getHisId() );
			        UserInfo userInfo2 = userInfoMapper.selectByPrimaryKey(title.getUserId());
					AppPush.sendPush(object,userInfo2.getUserPhone().split(","));
					
					SmsSendUtil.sendSmsNotify(title.getUserId(), history.getHisId(), 111, "恭喜！系统赠送了您"+valNum+"金币，快去我的财富查看吧~点击可查看");
					
					//更新金币排行榜
					updateGoldRank(history, userAccount);*/
				}else if(title.getOrderType() == 9)
				{
					GoldHistory history = new GoldHistory();
					history.setCreateTime(new Date());
					history.setHisId(UUID.randomUUID().toString().replace("-", ""));
					history.setHisType(12);
					history.setIsDel(1);
					history.setIsFinish(1);
					history.setOpType(1);
					history.setParamId(title.getId().toString());
					history.setUserId(title.getUserId());
					history.setValNum(Long.parseLong(title.getDiscount()));
					goldHistoryMapper.insertSelective(history);	
					UserAccount userAccount = userAccountMapper.selectByUserId(title.getUserId());
					userAccount.setGold(userAccount.getGold()+Integer.parseInt(title.getDiscount()));
					userAccountMapper.updateByPrimaryKey(userAccount);
				}
				
				logger.info("----------支付后续业务处理完毕--------------");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			flag = false;
			logger.info("---------------订单异常，插入订单异常表-------------------");
			RedisUtil.lpush(RedisConstants.ORDER_EXCEPTION.getBytes(), SerializeUtil.serialize(title));
			throw e;
		}
		return flag;
	}
	
	/**
	 * 更新当月金币排行榜
	 * @author Han Guohong
	 * @param history
	 * @param userAccount
	 */
	public void updateGoldRank(GoldHistory history,UserAccount userAccount){		
		userAccount.setGold(userAccount.getGold()+history.getValNum().intValue());
		
		Calendar calendar = Calendar.getInstance();
		int nowMonth = calendar.get(Calendar.MONTH)+1;
		
		//最后一次更新时间
		Date lastUpdate = userAccount.getLastUpdate();
		calendar.setTime(lastUpdate);
		int lastUpdateMonth = calendar.get(Calendar.MONTH)+1;
		
		if(nowMonth == lastUpdateMonth){//汇总当月
			
		}else{//汇总上月
			BigDecimal goldMonth = userAccount.getGoldMonth() == null ? new BigDecimal("0") : userAccount.getGoldMonth();
			userAccount.setGoldRechageQuarter(goldMonth);
			userAccount.setGoldMonth(new BigDecimal("0"));
		}
		
		BigDecimal val = new BigDecimal(history.getValNum()).divide(new BigDecimal("100"));
		
		BigDecimal goldMonth = userAccount.getGoldMonth() == null ? new BigDecimal("0") : userAccount.getGoldMonth();
		goldMonth = goldMonth.add(val);
		userAccount.setGoldMonth(goldMonth);
		
		BigDecimal goldRechageTotal = userAccount.getGoldRechageTotal() == null ? new BigDecimal("0") : userAccount.getGoldRechageTotal();
		goldRechageTotal = goldRechageTotal.add(val);
		userAccount.setGoldRechageTotal(goldRechageTotal);
		
		userAccount.setLastUpdate(new Date());
		
		userAccountMapper.updateByPrimaryKey(userAccount);
		
		if(RedisUtil.llen(RedisConstants.GOLD_RANK.getBytes())==0){
			RedisUtil.lpush(RedisConstants.GOLD_RANK.getBytes(), SerializeUtil.serialize(1));
		}
	}
	
	/**
	 * 更新当月土豪榜排名
	 * @author Han Guohong
	 * @param title
	 * @param userAccount
	 */
	private void updatePayRank(OrderInfo title,UserAccount userAccount){
		if(userAccount.getPayMoneyMonth() == null){
			userAccount.setPayMoneyMonth(new BigDecimal("0"));
		}
		//userAccount.setPayMoneyMonth(userAccount.getPayMoneyMonth()+title.getPayMoney());
		
		Calendar calendar = Calendar.getInstance();
		int nowMonth = calendar.get(Calendar.MONTH)+1;
		
		//最后一次更新时间
		Date lastUpdate = userAccount.getLastPaytime();
		
		if(lastUpdate == null){//汇总当月
			
		}else{
			calendar.setTime(lastUpdate);
			int lastUpdateMonth = calendar.get(Calendar.MONTH)+1;
			
			if(nowMonth == lastUpdateMonth){//汇总当月
				
			}else{//汇总上月
				BigDecimal totalNum = new BigDecimal("0");
				if(userAccount.getPayMoney() != null){
					totalNum = userAccount.getPayMoney();
				}
				userAccount.setPayMoneyQuarter(userAccount.getPayMoneyMonth());
				userAccount.setPayMoneyMonth(new BigDecimal("0"));
			}
		
		}
		
		BigDecimal val = new BigDecimal(title.getPayMoney()).divide(new BigDecimal("100"));
		
		BigDecimal payMoneyMonth = userAccount.getPayMoneyMonth();
		payMoneyMonth = payMoneyMonth.add(val);
		userAccount.setPayMoneyMonth(payMoneyMonth);
		
		BigDecimal payMoneyTotal = userAccount.getPayMoney() == null ? new BigDecimal("0") : userAccount.getPayMoney();
		payMoneyTotal = payMoneyTotal.add(val);
		userAccount.setPayMoney(payMoneyTotal);
		
		userAccount.setLastPaytime(new Date());
		
		userAccountMapper.updateByPrimaryKey(userAccount);
		
		if(RedisUtil.llen(RedisConstants.BUY_RANK.getBytes())==0){
			RedisUtil.lpush(RedisConstants.BUY_RANK.getBytes(), SerializeUtil.serialize(1));
		}
	}
}
